<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { useTableList } from './composables/useTableList'
import UserForm from './components/UserForm.vue'

const {
  tableData,
  pagination,
  loading,
  getList,
  handlePageChange,
  handleSizeChange,
  handleDelete,
  createUser,
  updateUser
} = useTableList()

const dialogVisible = ref(false)
const editingUser = ref(null)

const genderMap = {
  male: { label: '男', type: 'primary' },
  female: { label: '女', type: 'success' }
}

const handleAdd = () => {
  editingUser.value = null
  dialogVisible.value = true
}

const handleEdit = (row) => {
  editingUser.value = row
  dialogVisible.value = true
}

const handleSubmit = async (data) => {
  try {
    if (editingUser.value) {
      await updateUser(editingUser.value.uid, data)
      ElMessage.success('更新成功')
    } else {
      await createUser(data)
      ElMessage.success('创建成功')
    }
    dialogVisible.value = false
    getList()
  } catch (error) {
    ElMessage.error('操作失败')
  }
}

onMounted(() => {
  getList()
})
</script>

<template>
  <div class="container mx-auto">
    <div class="mb-4">
      <el-button type="primary" @click="handleAdd">新增用户</el-button>
    </div>

    <el-table v-loading="loading" :data="tableData" border>
      <el-table-column prop="uid" label="ID" width="80" />
      <el-table-column prop="name" label="姓名" />
      <el-table-column prop="gender" label="性别" width="100">
        <template #default="{ row }">
          <el-tag :type="genderMap[row.gender]?.type">
            {{ genderMap[row.gender]?.label }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200" fixed="right">
        <template #default="{ row }">
          <el-button type="primary" size="small" @click="handleEdit(row)">编辑</el-button>
          <el-popconfirm
            title="确定删除该用户吗？"
            @confirm="handleDelete(row.uid)"
          >
            <template #reference>
              <el-button type="danger" size="small">删除</el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

    <div class="mt-4 flex justify-end">
      <el-pagination
        v-model:current-page="pagination.current"
        v-model:page-size="pagination.pageSize"
        :total="pagination.total"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next"
        @size-change="handleSizeChange"
        @current-change="handlePageChange"
      />
    </div>

    <UserForm
      v-model:visible="dialogVisible"
      :edit-data="editingUser"
      @submit="handleSubmit"
    />
  </div>
</template>

<style scoped>
.container {
  padding: 20px;
}
</style>
